"use client";

import { useEffect, useState, useCallback, Suspense } from "react";
import { BookOpen, Loader2 } from "lucide-react";
import { ExamCard } from "@/components/exam-card";
import { useLanguage } from "@/context/language-provider";
import { useSearchParams } from "next/navigation";

interface Exam {
  考试日期: string;
  星期: string;
  时间: string;
  课程名称: string;
  课程英文名?: string;
  年级: string;
  专业名称: string | string[];
  source: string;
}

type DateRange = "3days" | "7days" | "month";

interface RecentExamsProps {
  initialDateRange?: DateRange;
  onDateRangeChange?: (range: DateRange) => void;
  onShare?: (url: string) => void;
}

// 创建一个单独的组件来处理URL参数
function URLParamsHandler({ onParamsChange }: { onParamsChange: (isInt: boolean) => void }) {
  const searchParams = useSearchParams();
  
  // 监听URL参数的变化
  const isIntByUrl = searchParams.get('int') === 'true';
  
  // 当URL参数变化时通知父组件
  useEffect(() => {
    onParamsChange(isIntByUrl);
  }, [isIntByUrl, onParamsChange]);
  
  return null;
}

export default function RecentExams({ initialDateRange = "3days", onDateRangeChange, onShare }: RecentExamsProps) {
  
  const [exams, setExams] = useState<Exam[]>([]);
  const [loading, setLoading] = useState(true);
  const [dateRange, setDateRange] = useState<DateRange>(initialDateRange);
  const [filteredExams, setFilteredExams] = useState<Exam[]>([]);
  const { language, isInternational: isIntByLanguage } = useLanguage();
  
  // 使用状态来存储URL参数值
  const [isIntByUrl, setIsIntByUrl] = useState(false);
  
  // 处理URL参数变化的回调
  const handleURLParamsChange = useCallback((isInt: boolean) => {
    setIsIntByUrl(isInt);
  }, []);
  
  // 同时检查语言设置和URL参数
  const isInternational = isIntByLanguage || isIntByUrl;

  // 当父组件的initialDateRange变化时，更新本地状态
  useEffect(() => {
    setDateRange(initialDateRange);
  }, [initialDateRange]);

  // 获取考试数据
  useEffect(() => {
    let isMounted = true;
    
    async function fetchExams() {
      try {
        setLoading(true);
        
        // 等待页面完全加载
        if (document.readyState !== 'complete') {
          await new Promise(resolve => {
            window.addEventListener('load', resolve, { once: true });
            // 如果页面已经加载完成但事件未触发，设置超时
            setTimeout(resolve, 1000);
          });
        }
        
        // 额外延迟，确保语言状态和URL参数已被正确处理
        await new Promise(resolve => setTimeout(resolve, 100));
        
        // 确保组件仍然挂载在DOM上
        if (!isMounted) return;
        
        // 添加int参数，国际版请求国际考试数据
        const response = await fetch(`/api/exams?recent=true${isInternational ? '&int=true' : ''}`);
        const data = await response.json();
        
        if (isMounted && data.exams && Array.isArray(data.exams)) {
          // 不再处理专业名称字段，保留原始格式
          setExams(data.exams);
        }
      } catch (error) {
        // 错误处理
        console.error("获取考试数据失败", error);
      } finally {
        if (isMounted) {
          setLoading(false);
        }
      }
    }

    fetchExams();
    
    return () => {
      isMounted = false;
    };
  }, [isInternational]); // 使用isInternational作为依赖

  // 当 dateRange 或 exams 变化时重新筛选考试
  useEffect(() => {

    
    // 根据选择的日期范围筛选考试
    function filterExams() {
      // 过滤掉重复的考试
      const uniqueExams = exams.reduce((acc: Exam[], exam) => {
        // 检查是否已经有相同的课程名称和日期
        const isDuplicate = acc.some(
          e => e.课程名称 === exam.课程名称 && e.考试日期 === exam.考试日期 && e.时间 === exam.时间
        );
        
        if (!isDuplicate) {
          acc.push(exam);
        }
        return acc;
      }, []);


      // 根据选择的时间范围过滤考试
      const filtered = uniqueExams.filter(exam => {
        // 处理日期，支持多种格式
        let examDateStr = exam.考试日期;
        let examDate: Date;
        
        // 检查是否包含年份
        if (/^\d{1,2}月\d{1,2}日$/.test(examDateStr)) {
          // 日期格式如 "4月21日"，添加当前年份
          const currentYear = new Date().getFullYear();
          examDateStr = `${currentYear}/${examDateStr.replace('月', '/').replace('日', '')}`;
        } else {
          // 标准格式，将"-"替换为"/"
          examDateStr = examDateStr.replace(/-/g, '/');
        }
        
        examDate = new Date(examDateStr);
        
        if (isNaN(examDate.getTime())) {
          console.warn(`无效日期: ${exam.考试日期} (转换后: ${examDateStr})`);
          return false; // 日期无效
        }
        
        const today = new Date();
        today.setHours(0, 0, 0, 0); // 设置为今天的开始
        
        const diffTime = examDate.getTime() - today.getTime();
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        
        let isIncluded = false;
        
        switch (dateRange) {
          case "3days":
            isIncluded = diffDays >= -3 && diffDays <= 3;
            break;
          case "7days":
            isIncluded = diffDays >= -7 && diffDays <= 7;
            break;
          case "month":
            // 当月考试
            isIncluded = examDate.getMonth() === today.getMonth() && 
                examDate.getFullYear() === today.getFullYear();
            break;
          default:
            isIncluded = true;
        }
     
        
        return isIncluded;
      });
      
      
      // 按日期排序
      const sorted = [...filtered].sort((a, b) => {
        // 处理排序时的日期
        let dateStrA = a.考试日期;
        let dateStrB = b.考试日期;
        
        // 为无年份日期添加年份
        if (/^\d{1,2}月\d{1,2}日$/.test(dateStrA)) {
          const currentYear = new Date().getFullYear();
          dateStrA = `${currentYear}/${dateStrA.replace('月', '/').replace('日', '')}`;
        } else {
          dateStrA = dateStrA.replace(/-/g, '/');
        }
        
        if (/^\d{1,2}月\d{1,2}日$/.test(dateStrB)) {
          const currentYear = new Date().getFullYear();
          dateStrB = `${currentYear}/${dateStrB.replace('月', '/').replace('日', '')}`;
        } else {
          dateStrB = dateStrB.replace(/-/g, '/');
        }
        
        const dateA = new Date(dateStrA);
        const dateB = new Date(dateStrB);
        return dateA.getTime() - dateB.getTime();
      });
      
     
      
      setFilteredExams(sorted);
    }
    
    filterExams();
    
  }, [exams, dateRange]);

  // 显示所有过滤后的考试，不再限制数量
  const displayExams = filteredExams;

  // 切换日期范围 - 使用useCallback确保函数引用稳定
  const handleDateRangeChange = useCallback((range: DateRange) => {
   
    if (range !== dateRange) {
      setDateRange(range);
      // 通知父组件日期范围变化
      if (onDateRangeChange) {
        onDateRangeChange(range);
      }
    }
  }, [dateRange, onDateRangeChange]);


  return (
    <>
      {/* 使用Suspense包装使用useSearchParams的组件 */}
      <Suspense fallback={null}>
        <URLParamsHandler onParamsChange={handleURLParamsChange} />
      </Suspense>
      
      {loading ? (
        <div className="flex justify-center py-12">
          <div className="flex flex-col items-center">
            <Loader2 className="h-8 w-8 animate-spin text-primary" />
            <span className="mt-2" style={{ color: 'hsl(var(--foreground) / 0.6)' }}>
              {language === "zh" ? "加载中..." : "Loading..."}
            </span>
          </div>
        </div>
      ) : displayExams.length === 0 ? (
        <div className="glass-card flex flex-col items-center justify-center py-16 gap-6 border-dashed"
             style={{ backgroundColor: 'hsl(var(--card) / 0.5)' }}>
          <div className="relative">
            <div className="absolute -inset-4 rounded-full animate-pulse blur-xl"
                 style={{ backgroundColor: 'hsl(var(--primary) / 0.1)' }}></div>
            <BookOpen className="w-16 h-16 text-primary relative" />
          </div>
          <div className="text-center space-y-2">
            <p className="text-xl font-medium">
              {language === "zh" ? "当前时间范围内暂无考试安排" : "No exams scheduled in the current time range"}
            </p>
            <p style={{ color: 'hsl(var(--foreground) / 0.6)' }} className="max-w-md">
              {language === "zh" ? "尝试选择不同的时间范围或稍后查看" : "Try selecting a different time range or check back later"}
            </p>
          </div>
        </div>
      ) : (
        <div className="grid gap-4 sm:gap-6 grid-cols-1 md:grid-cols-2 lg:grid-cols-3 auto-rows-fr">
          {displayExams.map((exam, index) => (
            <ExamCard
              key={`${exam.课程名称 || exam.课程英文名 || "unknown"}-${exam.考试日期}-${index}`}
              date={exam.考试日期}
              weekday={exam.星期}
              time={exam.时间}
              name={exam.课程名称 || ""}
              englishName={exam.课程英文名}
              grade={exam.年级}
              majors={exam.专业名称}
              onShare={onShare}
            />
          ))}
        </div>
      )}
    </>
  );
} 